<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="机器ID" prop="machineCode">
        <el-input
          v-model="queryParams.machineCode"
          placeholder="请输入机器ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机器编号" prop="machineNumber">
        <el-input
          v-model="queryParams.machineNumber"
          placeholder="请输入机器编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机器名称" prop="machineName">
        <el-input
          v-model="queryParams.machineName"
          placeholder="请输入机器名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="生产工艺" prop="processId">
        <el-select v-model="selectedProcessName" clearable class="!w-240px" @change="handleProcessNameChange">
          <el-option v-for="item in processNameList" :key="item.id" :label="item.processName" :value="item.id" />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="生产工艺" prop="processId">-->
<!--        <el-select-->
<!--          v-model="queryParams.processId"-->
<!--          placeholder="请选择生产工艺"-->
<!--          clearable-->
<!--          class="!w-240px"-->
<!--        >-->
<!--          <el-option label="请选择字典生成" value="" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:base-machine:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:base-machine:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      highlight-current-row
      @current-change="handleCurrentChange"
    >
<!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="机器ID" align="center" prop="machineCode" />
      <el-table-column label="机器编号" align="center" prop="machineNumber" />
      <el-table-column label="机器名称" align="center" prop="machineName" />
<!--      <el-table-column label="生产工艺" align="center" prop="processId" />-->
      <el-table-column label="生产工艺" align="center">
        <template #default="{ row }">
          {{ getProcessNameById(row.processId) }}
        </template>
      </el-table-column>
      <el-table-column label="产能" align="center" prop="capacity" />
      <el-table-column label="换款时间" align="center" prop="transferTime" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:base-machine:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:base-machine:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BaseMachineForm ref="formRef" @success="getList" />
  <!-- 子表的列表 -->
  <ContentWrap>
    <el-tabs model-value="baseMachineParameter">
      <el-tab-pane label="参数" name="baseMachineParameter">
        <BaseMachineParameterList :machine-id="currentRow.id" />
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { BaseMachineApi, BaseMachineVO } from '@/api/erp/basemachine'
import BaseMachineForm from './BaseMachineForm.vue'
import BaseMachineParameterList from './components/BaseMachineParameterList.vue'
import {BaseMaterialApi} from "@/api/erp/basematerial";

/** ERP基础资料-生产机器 列表 */
defineOptions({ name: 'BaseMachine' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<BaseMachineVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  machineCode: undefined,
  machineNumber: undefined,
  machineName: undefined,
  processId: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BaseMachineApi.getBaseMachinePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BaseMachineApi.deleteBaseMachine(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BaseMachineApi.exportBaseMachine(queryParams)
    download.excel(data, 'ERP基础资料-生产机器.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 选中行操作 */
const currentRow = ref({}) // 选中行
const handleCurrentChange = (row) => {
  currentRow.value = row
}


// 材质类型下拉框
const processNameList = ref<{ id: string; processName: string }[]>([]);

// const queryParams = ref({ materialTypeId: "" });
// **获取材质类型数据**
const getBaseMaterialType = async () => {
  try {
    const response = await BaseMachineApi.getAllProcess();
    if (response) {
      processNameList.value = response;
    }
  } catch (error) {
    console.error("获取工序信息失败：", error);
  }
};

/** 显示工序名称 */
const getProcessNameById = (id) => {
  const process = processNameList.value.find((p) => p.id === id)
  return process ? process.processName : '-'
}

/** 绑定工序选择 */
const selectedProcessName = ref(null)
const handleProcessNameChange = (id: string) => {
  queryParams.processId = id
}

/** 初始化 **/
onMounted(() => {
  Promise.all([getList(), getBaseMaterialType()]);
})
</script>
